package org.altoro.trongeventquery.transactions;

import com.alibaba.fastjson.JSONObject;
import org.altoro.trongeventquery.query.QueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Component
public class TransactionController {
    @Autowired(required = false)
    MongoTemplate mongoTemplate;

    @RequestMapping(method = RequestMethod.GET, value = "/transactions/total")
    public Long totaltransaction() {
        QueryFactory query = new QueryFactory();
        long number = mongoTemplate.count(query.getQuery(), TransactionTriggerEntity.class);
        return number;
    }


    @RequestMapping(method = RequestMethod.GET, value = "/transactions/totalAmount")
    public String totalAmount() {
        TypedAggregation<TransactionTriggerEntity> agg = Aggregation.newAggregation(TransactionTriggerEntity.class,
                Aggregation.match(Criteria.where("contractType").is("TransferContract")),
                Aggregation.group("assetAmount").sum("assetAmount").as("totalAmount"),
                Aggregation.project("totalAmount"));
        AggregationResults<String> result = mongoTemplate.aggregate(agg, String.class);
        return result.getMappedResults().get(0);
    }


    @RequestMapping(method = RequestMethod.GET, value = "/transactions")
    public JSONObject getTranssactions(
            /******************* Page Parameters ****************************************************/
            @RequestParam(value = "limit", required = false, defaultValue = "15") int limit,
            @RequestParam(value = "sort", required = false, defaultValue = "-timeStamp") String sort,
            @RequestParam(value = "start", required = false, defaultValue = "0") int start,
            @RequestParam(value = "contractType", required = false, defaultValue = "") String contractType,
            /****************** Filter parameters *****************************************************/
            @RequestParam(value = "address", required = false, defaultValue = "") String address,
            @RequestParam(value = "block", required = false, defaultValue = "-1") long block
    ) {
        QueryFactory query = new QueryFactory();
        if (block > 0) {
            query.setBlockNumGte(block);
        }
        if (contractType.length() != 0) {
            query.setContractTypeEqual(contractType);
        }
        if (address.length() != 0) {
            query.setAddressEqual(address);
        }
        query.setPageniate(QueryFactory.setPagniateVariable(start, limit, sort));
        List<TransactionTriggerEntity> queryResult = mongoTemplate.find(query.getQuery(),
                TransactionTriggerEntity.class);
        Map map = new HashMap();

        QueryFactory queryTotal = new QueryFactory();
        if (block > 0) {
            queryTotal.setBlockNumGte(block);
        }
        if (block > 0) {
            queryTotal.setBlockNumGte(block);
        }
        if (contractType.length() != 0) {
            queryTotal.setContractTypeEqual(contractType);
        }
        if (address.length() != 0) {
            queryTotal.setAddressEqual(address);
        }
        map.put("total", mongoTemplate.count(queryTotal.getQuery(), TransactionTriggerEntity.class));
        map.put("size", queryResult.size());
        map.put("data", queryResult);
        return new JSONObject(map);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/transactions/{hash}")
    public JSONObject getTransactionbyHash(
            @PathVariable String hash
    ) {

        QueryFactory query = new QueryFactory();
        query.setTransactionIdEqual(hash);
        List<TransactionTriggerEntity> queryResult = mongoTemplate.find(query.getQuery(),
                TransactionTriggerEntity.class);
        if (queryResult.size() == 0) {
            return null;
        }
        Map map = new HashMap();
        map.put("transaction", queryResult.get(0));

        return new JSONObject(map);
    }
}
